<template>
    <div>
        <!-- 添加栏目 -->
        <el-form :inline="true">
            <el-form-item>
                <el-select v-model="category_id" placeholder="父级" style="width: 240px" clearable>
                    <el-option v-for="item in tableData" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input v-model="name" placeholder="名称" autofocus="true" @keyup.enter="submit" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">添加</el-button>
            </el-form-item>
        </el-form>

        <un-category-webs v-if="unCategoryWebItems" :webs="unCategoryWebItems"
            :categories="allCategories"></un-category-webs>

        <web-category-item v-else v-for="item in tableData" :item="item"
            :rootCategories="allCategories"></web-category-item>

    </div>
</template>

<script setup>
import unCategoryWebs from "@/components/unCategoryWeb.vue";
import webCategoryItem from "@/components/webCategoryItem.vue";
import config from "@/config";
import router from "@/router";
import { get, post } from "@/utils/http";
import { onMounted, reactive, ref } from "vue";



const category_id = ref(0)
const name = ref("")
const tableData = reactive([])
const unCategoryWebItems = ref(null)
const allCategories = ref([])



onMounted(async () => {
    get(config.config.getAllWebCategories).then((resp) => {
        if (resp.data.errCode == 0) {
            allCategories.value = resp.data.items
        }
    })

    let resp = await get(config.config.getUnCategoryWeb)
    if (resp.data.errCode == 0 && resp.data.webs.length > 0) {
        unCategoryWebItems.value = resp.data.webs
    }

    if (resp.data.errCode != 0 || resp.data.webs.length == 0) {
        get(config.config.getWebCategory + "?private=true").then((resp) => {
            if (resp.data.errCode == 0) {
                for (const item of resp.data.items) {
                    if (item.category_id == 0) {
                        tableData.push(item)
                    }
                }
            }
            // category_id设置为上次内容
            category_id.value = parseInt(localStorage.getItem("category_id") || 0)
        })
    }
})


const submit = () => {
    if (name.value.length < 1) {
        return
    }
    post(config.config.addWebCategory, { "name": name.value, "category_id": category_id.value }).then((resp) => {
        let res = resp.data
        if (res.errCode != 0) {
            alert(res.data)
        } else {
            localStorage.setItem("category_id", category_id.value)
            router.go(0)
        }
    })
}
</script>

<style scoped>
.form {
    width: 100%;
}
</style>
